<?php
defined('ACCESS') or die ('Restricted Access');
require_once ('includes/system.clean.php');
class ObjInput{
	protected static $arrValueGet = array (); //@param mang luu gia tri cac bien GET tu url	
	protected static $arrValueObjectDefault = array(); //@param mang luu cac gia tri mac dinh khoi tao cua 1 object
	protected static $arrObjectIsCreate = array(); // @param mang lua cac object da duoc khoi tao roi
    protected static $ip_address            = FALSE;
	function __construct() {
	}
	/***
	 *	Function name: get
	 *	description Ham lay gia tri tu form hoac tu url
	 * @param $varName Ten param can lay gia tri
	 * @param $type - Kieu du lieu can tra ve
	 * @param $defaultValue - Gia tri mac dinh duoc truyen vao
	 * @param $method - Phuong thuc GET or POST or FILES, default ""
	 * @return Gia tri theo kieu $type duoc truyen vao
	 * @note Bat buoc phai truyen du 2 doi so $varName, $type
		
	 ***/
	public static function get($varName, $type, $defaultValue = '', $method = '') {
		$value = null;
		switch ($method) {
			case 'GET' :
				
				if (self::$arrValueGet [$varName]) {
					return self::$arrValueGet [$varName];
				
				} else {
					$value = $_GET [$varName];
					break;
				}
			case 'POST' :
				$value = $_POST [$varName];				
				break;
			case 'FILES' :
				$value = $_FILES [$varName];
				break;
			default :
				if (isset( $_POST [$varName] ))
					$value = $_POST [$varName];
				else if (isset( $_GET [$varName] ))
					$value = $_GET [$varName];
				else if (isset( $_REQUEST [$varName] ))
					$value = $_REQUEST [$varName];
				else if (isset( $_FILES [$varName] ))
					$value = $_FILES [$varName];
				break;
		
		}
		
		if (!isset($value))
			$value = $defaultValue;
		
		$value = self::doConvertType ( $value, $type );
		
		if ($method == 'GET' && ! self::$arrValueGet [$varName])
			self::$arrValueGet [$varName] = $value;
		return $value;
	}
	
	/***
	 *	Function name: doConvertType
	 *	description Ham convert du lieu theo kieu du lieu duoc truyen vao
	 * @param $value - gia tri can convert
	 * @param $type - Kieu du lieu can convert			
	 * @return Gia tri moi duoc convert theo dinh kieu $type
		
	 ***/
	public static function doConvertType($value, $type) {
		$objClean = ObjInput::createObject('objClean');//new objClean();
		switch ($type) {
			case 'def' :
				//$newValue = $value;
				if(!is_array($value)) $value = stripcslashes($value);
				$newValue = $objClean->xss_clean($value);
				break;
			case 'int' :
				$newValue = ( int ) $value;
				break;
			case 'double' :
				$value = str_replace ( '.', '', $value );
				$value = str_replace ( ',', '.', $value );
				$newValue = doubleval ( $value );
				break;
			case 'currency_format' :
				$newValue = self::currencyFormat ( $value );
				break;
			case 'str' :
				if($value)
				{	
                    $newValue = strip_tags($value); 			    
				}
				else 
					$newValue = '';
				
				break;
            case 'richtext' :
                if($value)
                {                    
                    $newValue = ObjInput::removeWordTag($value);
                    //$newValue = $objClean->xss_clean($newValue); 
                }
                else 
                    $newValue = '';
                
                break;
            case 'password' :
                if($value)
                {
                    $newValue = $value;
                }
                else 
                    $newValue = '';
                
                break;
			case 'sql' :
				$value = str_replace ( array('&quot;','"',"'","\\"), '', $value );
				$newValue = $value;
				break;		
			default :
				//if (get_magic_quotes_gpc () == 0 and is_string($value) and strlen($value) > 0)
				//	$value = addcslashes ( $value );
				//$newValue = htmlspecialchars ( $value );
				$newValue = $objClean->xss_clean(stripcslashes($value));
				break;
		
		}
		return $newValue;
	}
	
	/***
	 *	Function name currencyFormat
	 *	description Ham dinh dang so theo chuan 	
	 * @param $value - gia tri can dinh dang		
	 * @return Gia tri da duoc dinh dang
	 * @description ex: dau vao $value = 1000000 ket qua tra ve 1.000.000
		
	 ***/
     static function strip_word_html($text)
    {
        $text = preg_replace(
        array(
            // Remove invisible content
            '@<head[^>]*?>.*?</head>@siu',
            '@<style[^>]*?>.*?</style>@siu',
            '@<script[^>]*?.*?</script>@siu',
            '@<object[^>]*?.*?</object>@siu',
            '@<embed[^>]*?.*?</embed>@siu',
            '@<applet[^>]*?.*?</applet>@siu',
            '@<noframes[^>]*?.*?</noframes>@siu',
            '@<noscript[^>]*?.*?</noscript>@siu',
            '@<noembed[^>]*?.*?</noembed>@siu',

            // Add line breaks before & after blocks
            '@<((br)|(hr))@iu',
            '@</?((address)|(blockquote)|(center)|(del))@iu',        
            '@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
            '@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
            '@</?((table)|(th)|(td)|(caption))@iu',
            '@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
            '@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
            '@</?((frameset)|(frame)|(iframe))@iu',
        ),
        array(
            ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
            "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
            "\n\$0", "\n\$0",
        ),
        $text );

    // Remove all remaining tags and comments and return.
    return  $text ;
    }
	static function currencyFormat($value) {
		if($value != '' and is_numeric($value))
		{
    	    $value = number_format ( $value, 2, ',', '.' );
    		$value = str_replace ( ',00', '', $value );
		}
		return $value;
	}
	/***
	 *	Function name unCurrencyFormat
	 *	description Ham chuyen doi ve kieu so chuan trong mysql de luu tru 	
	 * @param $value - gia tri can dinh dang
	 * @param $isDb - Du lieu lay tu db hay tu web		
	 * @return Gia tri da duoc dinh dang
	 * @description ex: dau vao $value = 1.000.000,56 ket qua tra ve 1000000.56
		
	 ***/
	function unCurrentFormat($value, $isDb = false)
	{
		if($isDb == false)
		{
		    $value = str_replace('.','', $value);
		    $value = str_replace(',','.', $value);
		}
		else 
		{
			//$value = str_replace(',','.', $value);
			$value = str_replace('.',',', $value);
		}
	    return $value;
	}
	/***
	 *    Function name getImageFolder
	 *    description Ham tra ve thuc muc anh se duoc luu tru (su dung trong cac truong hop thu muc anh duoc phan nho theo thang, vi du nhu item)
	 *         
	 * @param $package - package duc luu anh 
     * @param $path - duong dan truyen vao
	 * @return path luu anh
	 * @ex voi $package = 'item', $path = 'data/images'
	 *      ket qua tra ve data/image/item/m_Y (d = date('m'), Y = data('Y'))
        
	 ***/
	
	static function getImageFolder($package = '', $path = 'data/images/') {
		$path .= $package . '/';
		$folder = date ( 'm' ) . '_' . date ( 'Y' );
		if (! is_dir ( $path . $folder )) {
			@mkdir ( $path . $folder );
			@mkdir ( $path . $folder . '/thumbs' );
		}
		return $path . $folder;
	}
	
	/***
	 *    Function name: getFolderMonthYear
	 *    description: Ham lay thu muc tu cac files co kieu luu tru m_Y_xxxx.yyy
	 *         
	 * @param $filename ten file
	 * @return folder kieu m_Y  
        
	 ***/
	static function getFolderMonthYear($filename) {
		$str = explode ( '_', $filename );
		return $str [0] . '_' . $str [1];
	}
	
	/***
	 *    description Function getCombo
	 *    description ham tra ve gia tri de ve combobox
	 *         
	 * @param $beginInt
     * @param $endInt
     * @param $selected: gia tri duoc chon hien tai
	 * @return string
        
	 ***/
	static function getCombo($beginInt, $endInt, $selected) {
		for($i = $beginInt; $i <= $endInt; $i ++) {
			$input .= '<option value="' . $i . '"';
			if ($i == $selected) {
				$input .= ' selected';
			}
			$input .= '>' . $i . '</option>';
		}
		return $input;
	}
    
    static function getComboDown($beginInt, $endInt, $selected) {
        for($i = $beginInt; $i >= $endInt; $i --) {
            $input .= '<option value="' . $i . '"';
            if ($i == $selected) {
                $input .= ' selected';
            }
            $input .= '>' . $i . '</option>';
        }
        return $input;
    }
	
	/***
	 *    Function name: getOption
	 *    description: ham tra ve du lieu ve option 
	 *         
	 * @param $options - mang gia tri cac option
     * @param $selected - gia tri duoc chon hien tai
	 * @return string
	 *         
	 ***/
	static function getOption($options, $selected) {
		if (is_array($options) and sizeof($options) > 0)
			foreach ( $options as $key => $text ) {
				$input .= '<option value="' . $key . '"';
				if ($key == $selected) {
					$input .= ' selected';
				}
				$input .= '>' . $text . '</option>';
			}
		return $input;
	}
    static function get_Option($options,$value,$name,$selected) {
		if (is_array($options) and sizeof($options) > 0)
        {
            foreach($options as $row)
            {
                $input .= '<option value="' . $row[$value] . '"';
				if ($row[$value] == $selected) {
					$input .= ' selected';
				}
				$input .= '>' . $row[$name] . '</option>';
            }
        }
		return $input;
	}
	/***
	 *    Function name: getMutileOption
	 *    description: ham tra ve du lieu ve option 
	 *         
	 * @param $options - mang gia tri cac option
     * @param $arrSelected - gia tri duoc chon hien tai
	 * @return string
	 *         
	 ***/
	static function getMutileOption($options, $arrSelected) {
		if(!is_array($arrSelected))
		    ObjInput::getOption($options, $arrSelected);
	    elseif(sizeof($arrSelected) === 0)
	        ObjInput::getOption($options, 0);
	    elseif (is_array($options) and sizeof($options))
			foreach ( $options as $key => $text ) {
				$input .= '<option value="' . $key . '"';
				if (in_array($key, $arrSelected)) {
					$input .= ' selected';
				}
				$input .= '>' . $text . '</option>';
			}
		return $input;
	}
	/***
	 *    Function name: getCheckboxList
	 *    description: ham tra ve du lieu ve checkbox 
	 *         
	 * @param $options - mang gia tri cac option
     * @param $selected - gia tri duoc chon hien tai
	 * @return string
	 *         
	 ***/
	static function getCheckboxList($options,$input_name,$selected,$br=' ') {
		if ($options)
			foreach ( $options as $key => $text ) {
				$input .= '<input type="checkbox" name="'.$input_name.'[]" id="'.$input_name.'[]" value="'.$key.'"';
				if (in_array($key,$selected)) {
					$input .= ' checked="checked" ';
				}
				$input .= '> ' .$text.$br;
			}
		return $input;
	}
	/***
	 *    Function name: getOption
	 *    description: ham tra ve du lieu ve option 
	 *         
	 * @param $options - mang gia tri cac option
     * @param $selected - gia tri duoc chon hien tai
	 * @return string
	 *         
	 ***/
	static function getRadioList($options,$input_name,$selected,$br=' ') {
		if ($options)
			foreach ( $options as $key => $text ) {
				$input .= '<input type="radio" name="'.$input_name.'" id="'.$input_name.'" value="'.$key.'"';
				if ($key==$selected) {
					$input .= ' checked="checked" ';
				}
				$input .= '> ' .$text.$br;
			}
		return $input;
	}
	
	/**
	 * Trả về một cấu trúc checkbox
	 * @param $options = array('name','value','title')
	 * @param $selected
	 * @param $ext
	 */
	static function getCheckbox($options=array(),$selected='',$ext=' ') {
		$input = '';
		if ($options){
			$input .= '<input type="checkbox"';
			if (isset($options['name'])) {
				$input .= ' name="'.$options['name'].'" id="'.$options['name'].'"';
			}
			if (isset($options['value'])) {
				$input .= ' value="'.$value.'"';
				if ($options['value']==$selected) {
					$input .= ' checked="checked" ';
				}
			} else {
				$input .= ' value=""';
			}
			
			$input .= '>';
			if (isset($options['title'])) {
				$input = '<label>'.$input.' '.$options['title'].'</label>';
			}
			$input .= $ext;
		}
		return $input;
	}
	
	/***
	 *    Function name: getOption
	 *    description: ham tra ve du lieu ve option 
	 *         
	 * @param 	$objectName - Ten doi tuong can khoi tao
     * @param 	$valueDefault - gia tri mac dinh
	 * @return object
	 *         
	 ***/
	static function createObject($objectName, $valueDefault = '') {
		
		if(is_object($valueDefault))
			return new $objectName($valueDefault);
		else
		{
			$object = self::$arrObjectIsCreate[$objectName];			
			if($valueDefault !== self::$arrValueObjectDefault[$objectName] || !is_object($object))
			{
				$object = new $objectName($valueDefault);
				self::$arrObjectIsCreate[$objectName] = $object;
				self::$arrValueObjectDefault[$objectName] = $valueDefault;
			}
			return $object;
		}		
	}
	/*
	 Lây page_no
	*/
	static function page_no($page_name='page_no')
	{
		$page_no=ObjInput::get($page_name,'int',1);
		if ($page_no<0)
		$page_no=1;
		return $page_no;
	}
	/***
	 *    Function name: convertSqlIn
	 *    description: Hàm xử lý 1 string cách nhau dấu phẩy về chỉ có số 
	 *         
	 * @param $str - Mảng đầu vào
	 * @return string
	 *         
	 ***/
	static function convertSqlIn($str) {
		if ($str)
			$a=explode(',',$str);
		$output='';
		if ($a)
		foreach ($a as $n)
		{
			$num=(int)$n;
			if (is_numeric($n) or $num>0)
			if ($output=='')
				$output=$num;
			else
				$output.=','.$num;
		}
		return $output;
	}	/***
	 *    Function name: getTablePartition
	 *    description: ham tra ve ten bang duoc phan tan
	 *         
	 * @param 	$name - Ten chung cua bang
     * @param 	$id - ma dung de phan tan
     * @param 	$level - so bang duoc phan tan
	 * @return object
	 *         
	 ***/
	static function getTablePartition($name, $id, $level=1)
	{
	  	$mod = $id%$level;
	  	return $name.$mod;
	}
	/**
	 * Ham lay dia chi ip cua mot client
	 *
	 * @return string
	 */
    static function getClientIp()
    {
        if (getenv('HTTP_CLIENT_IP'))
        {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        elseif (getenv('HTTP_X_FORWARDED_FOR'))
        {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_X_FORWARDED'))
        {
            $ip = getenv('HTTP_X_FORWARDED');
        }
        elseif (getenv('HTTP_FORWARDED_FOR'))
        {
            $ip = getenv('HTTP_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_FORWARDED'))
        {
            $ip = getenv('HTTP_FORWARDED');
        }
        else
        {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
     /**
     * Ham lay dia chi ip cua mot client
     *
     * @return string
     */
    static function convertSearch($text)
    {
         if($text)
         {
         	$text = str_replace(array('-','_', '/', '\\'), ' ', $text);
         	$text = str_replace(array('#',',',';','"',"'",'(',')','*','~','.','!','?',':',"[","]",",","»"), '', $text);
         	$arr = explode(' ', $text);
         	$text = '';
         	$total = count($arr);
         	for($i = 0; $i < $total; $i++)
         	{
         		$value = $arr[$i];
         		if($value != ' ')
         		{
         			if($text != '')
         				$text .= ' '.$value;
         			else
         				$text = $value;
         		}
         	}
         }
         return $text;
    }
    static function convertSSearch($text)
    {
		 if($text)
         {
         	$text = str_replace(array('-','_', '/', '\\'), ' ', $text);
         	$text = str_replace(array('#',',',';','"',"'",'(',')','*','~','.','!','?',':',"[","]",",","»"), '', $text);
         	$text = trim($text);
         	$arr = explode(' ', $text);
         	$text = '';
         	$total = count($arr);
         	for($i = 0; $i < $total; $i++)
         	{
         		$value = $arr[$i];
         		if($value != ' ')
         		{
         			if($text != '')
         				$text .= ' '.$value;
         			else
         				$text = $value;
         			if($i == 5)
         				break;
         		}
         	}
         }
         return $text;          
    }
    static function removeExternalLink($text)
    {
        //$text=str_replace('href',' rel="notfollow" href',$text);
        //return $text;
        // Optimize để chỉ đặt với domain ngoài CĐT
        $regex = '#(href=").*?(")#';
        preg_match_all($regex, $text, $matches);
        $links=$matches[0];
        if ($links)
        foreach ($links as $url)
        {
            if (!strpos($url,'chodientu.vn'))
            {    
                if (strpos($url,'remove')>0 or strpos($url,'mailto')>0 or strpos($url,'ref="http')>0)
                $text=str_replace($url,' rel="notfollow" '.$url,$text);
            }
        }
        return $text;
    }
    static function removeWordTag($text)
    {
      //  return $text;
        $text=str_replace(array('&lt;','&gt;'),array('<','>'),$text);
        require_once ROOT_PATH.DS.'system/utils/class.removeWord.php';
        $cleaner=new HTMLCleaner();
        $cleaner->Options['UseTidy']=false;
        $cleaner->Options['OutputXHTML']=false;
        $cleaner->Options['Optimize']=true;
        $cleaner->html=$text;
        $cleanHTML=$cleaner->cleanUp();
        unset($cleaner);
        if (strlen($cleanHTML)<50)
            return $text;
        else
            return $cleanHTML;
    }
}
?>